<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use Mine\MineModel;

/**
 * @property int $id 主键
 * @property int $tag_id 
 * @property int $material_id 
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 */
class ChMaterialToTag extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_material_to_tag';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'tag_id', 'material_id', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'tag_id' => 'integer', 'material_id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    /**
     * 绑定关系
     */
    public static function bindTag($materialId,$tagId)
    {
        self::query() -> create(['tag_id' => $tagId,'material_id'=>$materialId]);
    }

    public static function bindTags($tags,$materialId)
    {
        self::query() ->where('material_id',$materialId)->delete();
        if(is_string($tags)){
            $tags = explode(",",$tags);
        }
        foreach ($tags as $tag){
            self::bindTag($materialId,$tag);
        }
    }
}
